# 自定义模块


# 内置模块
#     random : 生成随机数
#       randint(a, b)	返回介于a和b之间的随机整数,包含a和b
#       choice(seq)	    从非空序列返回一个随机元素
#       shuffle(seq)	随机打乱一个序列,没有返回值,原地打乱
#       random()	    返回范围为[0.0，1.0）的下一个随机浮点数
#     time : 时间相关的模块
#     math : 数学模块

# import random
# print(random.randint(1,20))
# print(random.choice("abcdefg"))
# list_01 = [1,2,3,4,5,6,7,8,9]
# random.shuffle(list_01)
# print(list_01)
# print(random.random())
# #生成随机的大写字母
# print(chr(random.randint(65,90)))

# 题目:随机生成n位验证码(字母 a-z,A-Z)
# a-z : 97-122
# A-Z : 65-90
import random
def getCode(n):
    str = ""
    for i in range(n):
        num = random.randint(65, 122)
        # 减少了循环的有效次数(有效次数:真正可以给str进行拼接的次数)!
        if(num <=90 or num>=97):
            str += chr(num)

    #检查一下生成的字符串 是否 达到了指定位数
    if(len(str) < n):
        # 代表字符串的长度没有满足指定位数,少几个补几个
        str += getCode(n - len(str)) # 递归! 递归:函数自己调自己

    return str

# code = getCode(4)
# print(code)


# 第三方模块(pip)
# d40c4facd4d7a8b18756c9e4ea305954
import requests
def get_weather(api_key, city="Beijing", units="metric"):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": units
    }

    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # 检查HTTP错误
        weather_data = response.json()

        # 解析数据
        return {
            "城市": weather_data["name"],
            "天气": weather_data["weather"][0]["description"],
            "当前温度": weather_data["main"]["temp"],
            "体感温度": weather_data["main"]["feels_like"],
            "湿度": f"{weather_data['main']['humidity']}%",
            "风速": f"{weather_data['wind']['speed']} m/s"
        }

    except requests.exceptions.RequestException as e:
        return f"网络请求错误: {str(e)}"
    except KeyError:
        return "解析天气数据失败，请检查API响应格式"
    except Exception as e:
        return f"发生未知错误: {str(e)}"


# 使用示例
if __name__ == "__main__":
    API_KEY = "d40c4facd4d7a8b18756c9e4ea305954"  # 替换为你的API密钥
    city = input("请输入城市名称（默认北京）：") or "Beijing"

    weather = get_weather(API_KEY, city)
    if isinstance(weather, dict):
        print("\n当前天气情况：")
        for key, value in weather.items():
            print(f"{key}: {value}")
    else:
        print(weather)
























